<template>
  <div class="search">
    <div class="inputValue">
      <form action="/">
        <van-search
          v-model="inputValue"
          show-action
          placeholder="请输入搜索关键词"
          @search="onSearch"
          @cancel="onCancel"
          @keyup="inputval"
          class="colorBg"
        />
      </form>
    </div>
    <!-- 联想 -->
    <div class="info" v-if="this.upvalList.length">
      <span class="infoValue">联想区域</span>
      <i class="iconfont" @click="delSuggest">&#xe75e;</i>
    </div>
    <!-- 历史 -->
    <div class="info" v-else>
      <span class="infoValue">历史区域</span>
      <i class="iconfont" @click="delHistory">&#xe75e;</i>
    </div>
    <!-- 用户显示的联想区域 -->
    <div class="history" v-for="(item, index) in upvalList" :key="index">
      <i class="iconfont">&#xe7b5;</i>
      <span class="historyVal" v-html="item" @click="upClick(index)"></span>
    </div>
    <!-- 历史区域 -->
    <div v-if="!this.upvalList.length">
      <div class="history" v-for="(item2, index2) in historyList" :key="index2">
        <i class="iconfont">&#xe7b5;</i>
        <span class="historyVal" @click="historyClick(item2)">{{ item2 }}</span>
        <i class="iconfont right" @click="rightClick(index2)">&#xe75e;</i>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast, Dialog } from 'vant'
// 导入搜索方法 , appV10Search
import { appV10Suggestion } from '@/api/search.js'
// 导入token方法
import { setLocalToken, getLocalToken } from '@/utils/token.js'
export default {
  name: 'Search',
  data () {
    return {
      timer: null, // 定义一个联想区域，防抖定时器
      inputValue: '', // 用户输入的信息
      historyList: [], // 存储当前历史搜索
      upvalList: [], // 存储用户键盘按下的内容
      optionsList: [] // 存储用户键盘按下的内容（调用返回未修改的）
    }
  },

  async created () {
    console.log(JSON.parse(getLocalToken('history')))
    // console.log(getLocalToken('history'))
    this.historyList = JSON.parse(getLocalToken('history')) || []
  },

  methods: {
    // 键盘输入点击事件
    async onSearch (val) {
      // 判断输入内容是否为空，打断并提示
      if (!val.trim()) {
        Toast.fail('请输入搜索内容')
        return
      }
      console.log(val)
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 1000
      })
      // const res3 = await appV10Search({ q: val })
      // console.log(res3)
      // 回车后清空输入内容和存储按下数组
      if (val) {
        this.historyList.unshift(val)
      }
      this.historyList = [...new Set(this.historyList)].slice(0, 5)
      this.inputValue = ''
      this.upvalList = []
      // 存储输入的历史内容到本地
      console.log(this.historyList)
      setLocalToken('history', JSON.stringify(this.historyList))

      // 跳转搜索结果页面
      this.$router.push({
        path: '/home/SearchResult',
        query: {
          val
        }
      })
    },

    onCancel () {
      Toast('取消输入')
    },

    inputval () {
      // console.log('键盘按下了')
      if (this.inputValue.trim() === '') {
        this.upvalList = []
        return
      }
      console.log(this.inputValue)

      // 设置防抖
      if (this.timer) {
        clearTimeout(this.timer)
      }

      this.timer = setTimeout(async () => {
        const res2 = await appV10Suggestion({ q: this.inputValue })
        // 将搜索的关键字变成红色
        res2.data.options.forEach(item => {
          // console.log(item)
          const _arr = item.split(this.inputValue)
          // console.log(_arr)
          item = _arr.join(`<span style="color:red">${this.inputValue}</span>`)
          // console.log(item)
          item = _arr.join(item)
          // console.log(item)
          this.upvalList.push(item)
        })
        // 将键盘按下事件的内容调取接口，再把返回值存储在upvalList中，判断upvalList的length是否有
        this.upvalList = this.upvalList.reverse()
        // 去重
        this.upvalList = [...new Set(this.upvalList)]
        // 只显示联想的前面五条数据
        this.upvalList = this.upvalList.slice(0, 5)
        // console.log(this.upvalList)
        this.optionsList = res2.data.options.reverse()
        // console.log(this.optionsList)
      }, 1000)
    },

    // 联想区域的删除按钮点击事件
    delSuggest () {
      this.inputValue = ''
      this.upvalList = []
    },

    // 删除历史记录的点击事件
    delHistory () {
      console.log('del')
      Dialog.confirm({
        title: '清空所有历史记录！',
        message: '确定吗，亲？'
      })
        .then(() => {
          Dialog.confirm({
            title: '那些属于我们的回忆你真的不要了吗'
          })
            .then(() => {
              Toast('渣男')
              this.historyList = []
              // removeLocalToken('history')
              setLocalToken('history', [])
              // on confirm
            })
            .catch(() => {
              // on cancel
              Toast('我就知道你舍不得')
            })
          // on confirm
        })
        .catch(() => {
          // on cancel
        })
      //
    },

    // 历史渲染区域的子元素点击删除
    rightClick (index2) {
      // console.log(this.historyList)
      // this.historyList.remove(index2)
      this.historyList.splice(index2, 1)
      setLocalToken('history', JSON.stringify(this.historyList))
    },

    // 联想区域的点击搜索事件
    upClick (index) {
      // this.inputValue = item
      // console.log(this.optionsList[index])
      this.onSearch(this.optionsList[index])
    },
    // 搜索历史的点击事件
    historyClick (item2) {
      console.log(item2)
      this.onSearch(item2)
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  .inputValue {
    .colorBg {
      background: @color-bg;
    }
    .van-search__action {
      color: #ffffff;
      margin-right: 8px;
      margin-left: 8px;
    }
    .van-search__action:active {
      background-color: #3296fa;
      color: #fff;
    }
  }
  .info {
    padding: 10px 15px;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    font-family: MicrosoftYaHei;
    font-size: 14px;
    font-weight: normal;
    font-stretch: normal;
    line-height: 18px;
    letter-spacing: 1px;
    .iconfont {
      font-size: 22px;
    }
  }
  .history {
    padding: 0px 15px;
    height: 40px;
    width: 100%;
    line-height: 40px;
    font-size: 14px;
    // background-color: pink;
    span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .right {
      color: red;
      text-align: right;
      float: right;
      padding-right: 5px;
    }
  }
}
</style>
